import '../public.dart';

class GAccountItem extends AccountItem {
  late int originKey;
  GAccountItem(
      {String? name,
      String? id,
      String? pwd,
      String? remark,
      required String type,
      required this.originKey})
      : super(name: name, id: id, pwd: pwd, remark: remark, type: type);
}

class GroupInfo {
  String type;
  List<GAccountItem> list;
  GroupInfo({required this.type, required this.list});
}

class UserModel extends ChangeNotifier {
  List<AccountItem> accounts = [];
  UserModel() {
    init();
  }
  init() {
    var items = StorageManager.getItem('accounts');
    if (items != null) {
      accounts = List<AccountItem>.from(
          (items as List).map((item) => AccountItem.fromJson(item)));
    }
  }

  List<GroupInfo> get groups {
    List<String> types = [];
    for (var element in accounts) {
      if (!types.any((k) => (k == element.type))) {
        types.add(element.type);
      }
    }
    return types.map((ty) {
      List<GAccountItem> list = [];
      for (int i = 0; i < accounts.length; i++) {
        if (accounts[i].type == ty) {
          GAccountItem n = GAccountItem(
            name: accounts[i].name,
            id: accounts[i].id,
            pwd: accounts[i].pwd,
            type: accounts[i].type,
            remark: accounts[i].remark,
            originKey: i,
          );
          list.add(n);
        }
      }
      return GroupInfo(type: ty, list: list);
    }).toList();
  }

  void editAccount(AccountItem item, int index) {
    accounts.removeAt(index);
    accounts.add((item));
    StorageManager.setItem(
        'accounts',
        accounts.map((v) {
          return v.toJSONEncodable();
        }).toList());
    notifyListeners();
  }

  void addAccount(AccountItem item) {
    accounts.add((item));
    StorageManager.setItem(
        'accounts',
        accounts.map((v) {
          return v.toJSONEncodable();
        }).toList());
    notifyListeners();
  }

  void deleteAccount(int index) {
    accounts.removeAt(index);
    StorageManager.setItem(
        'accounts',
        accounts.map((v) {
          return v.toJSONEncodable();
        }).toList());
    notifyListeners();
  }

  void deleteGroup(String type) {
    accounts.removeWhere((element) => element.type == type);
    StorageManager.setItem(
        'accounts',
        accounts.map((v) {
          return v.toJSONEncodable();
        }).toList());
    notifyListeners();
  }
}
